<script lang="ts">
import { computed, defineComponent, reactive, ref, watch, PropType } from 'vue';

interface Person {
  name: string;
  age: number;
}

enum NodeType {
  TEXT = 'text',
  ELEMENT = 'element',
  COMPONENT = 'component',
}

export default defineComponent({
  name: 'DefineComponent',
  props: {
    name: {
      type: String, // 这个类型是一个构造函数 Number | String | Boolean | Array | Object | Function | Symbol 而不是 string这种
      default: 'John',
    },
    per: {
      type: Object as PropType<Person>, //Person Vue: Person only refers to a type, but is being used as a value here.
      required: false,
    },
    status: {
      type: [String, Number],
      default: 'positive',
    },
    season: {
      type: String as PropType<'spring' | 'summer'>,
      required: false,
      default: 'spring',
    },
    nodeType: {
      type: String as PropType<NodeType>,
      default: NodeType.TEXT,
    },
  },
  emits: ['update:name'],
  setup(props, context) {
    // context.emit('update:name', props.name);

    const count = ref<string | number>(0);
    const user = reactive<Person>({
      age: 10,
      name: 'John',
    });

    const status = computed(() => {
      return count.value > 10 ? 'positive' : 'negative';
    });

    const increment = () => {
      if (typeof count.value === 'number') {
        count.value = count.value + 1;
      }
    };

    watch(
      count,
      (newVal, oldVal) => {
        console.log(`count changed from ${oldVal} to ${newVal}`);
      },
      {
        immediate: true,
        flush: 'post', //默认的是组件更新之前被调用，设置为post可以延迟到组件更新之后才调用， 可以用document.getElementById('app').innerHTML来测试
      },
    );

    return {
      count,
      increment,
      user,
      status,
    };
  },
});
</script>

<template>
  <div>
    <div>{{ count }}</div>
    <div>{{ user.name }} - {{ user.age }}</div>
    <button @click="increment">{{ count }}===> {{ status }}</button>
  </div>
</template>

<style scoped lang="less"></style>
